<?php

/**
 * Class Document
 * @author Remi
 * @version 1.0
 */
class Document
{

    /**
     * @var int
     */
    private $Id;
    /**
     * @var int
     */
    private $IdStage;
    /**
     * @var string
     */
    private $Path;
    /**
     * @var int
     */
    private $DateUpload;
    /**
     * @var int
     */
    private $Type;
    /**
     *
     * @var int 
     */
    private $Required;
    /**
     * @var string
     */
    private $Statut;

    /**
     *
     * @param int $id
     */
    public function __construct($id = 0)
    {

        if (empty($id))
        {
            $this->Id = 0;
            $this->IdStage = 0;
            $this->Path = 0;
            $this->DateUpload = 0;
            $this->Statut = "";
            $this->Type = 0;
            $this->Required = 0;

            $this->requeteOk = true;
            $this->errormsg = "";
        }
        else
        {
            $sql = SQL::getInstance()->getConnection();
            //On retourne l'entree demandee
            $query = 'SELECT * FROM Document WHERE IdDocument = :id';
            $c = $sql->prepare($query);
            $c->bindParam(':id', $id, PDO::PARAM_INT);
            //Execution de la requête retourne false si echec
            if ($c->execute())
            {
                $result = $c->fetch(PDO::FETCH_OBJ);
                if (!empty($result))
                {
                    $this->Id = $result->IdDocument;
                    $this->IdStage = $result->IdStage;
                    $this->Path = $result->PathDocument;
                    $this->DateUpload = $result->DateUploadDocument;
                    $this->Statut = $result->StatutFichier;
                    $this->Type = $result->IdTypeDocument;
                    $this->Required = $result->IdRequiredDocument;
                }
                else
                {
                    $this->requeteOk = false;
                    $this->errormsg = "Ce document n'existe pas !";
                }
            }
            else
            {
                //Recuperation de l'erreur dans la variable de classe
                /*
                  Pour chaque new avec passage de paramètres vous pouvez savoir si vous avez bien un resultat, si false n'oubliez pas de gerez l'affichage du message,...
                 */
                $this->requeteOk = false;
                $this->errormsg = $c->errorInfo();
            }
        }
    }

    /**
     * Sauvegarde un Objet document dans la base
     */
    public function save()
    {
        if (isset($this->Id) && !empty($this->Id))
        {
            $sql = SQL::getInstance()->getConnection();
            $query =
                    'UPDATE Document
			SET 
				 IdStage = :stage,
				 PathDocument = :path,
				 IdTypeDocument = :type,
                 IdRequiredDocument = :required,
				 StatutFichier = :statut
			WHERE 
				IdDocument 	= :id';
            $sql->beginTransaction();
            try
            {
                $c = $sql->prepare($query);

                $c->bindParam(':id', $this->Id, PDO::PARAM_INT);
                $c->bindParam(":path", $this->Path, PDO::PARAM_STR);
                $c->bindParam(":type", $this->Type, PDO::PARAM_INT);
                $c->bindParam(":required", $this->Required, PDO::PARAM_INT);
                $c->bindParam(":statut", $this->Statut, PDO::PARAM_STR);


                if ($c->execute())
                {
                    $this->requeteOk = true;
                    $this->errormsg = "";
                    $sql->commit();
                    $c->closeCursor();
                }
                else
                {
                    $this->requeteOk = false;
                    $this->errormsg = $c->errorInfo();
                    $sql->rollback();
                    $c->closeCursor();
                }
            }
            catch (PDOException $Exception)
            {
                $this->requeteOk = false;
                $this->errormsg = $c->errorInfo();
                $sql->rollback();
                $c->closeCursor();
            }
        }
        else
        {
			$sql = SQL::getInstance()->getConnection();
            $query =
                    'INSERT INTO Document
			(
				 IdStage,
				 PathDocument,
				 DateUploadDocument,
				 IdTypeDocument,
                 IdRequiredDocument,
				 StatutFichier
			)
			VALUES
			(
				:idstage,
				:path,
				:upload,
				:type,
                :required,
				:statut
			)';
            $sql->beginTransaction();
            try
            {
                $c = $sql->prepare($query);

                $c->bindParam(":idstage", $this->IdStage, PDO::PARAM_INT);
                $c->bindParam(":path", $this->Path, PDO::PARAM_STR);
                $c->bindParam(":upload", time());
                $c->bindParam(":type", $this->Type, PDO::PARAM_INT);
                $c->bindParam(":required", $this->Required, PDO::PARAM_INT);
                $c->bindParam(":statut", $this->Statut, PDO::PARAM_STR);

                if ($c->execute())
                {
                    $this->Id = $sql->lastInsertId();
                    $sql->commit();
                    $c->closeCursor();
                    $this->requeteOk = true;
                    $this->errormsg = "";
                }
                else
                {
                    $this->requeteOk = false;
                    $this->errormsg = $c->errorInfo();
                    $sql->rollback();
                    $c->closeCursor();
                    $this->Id = 0;
                }
            }
            catch (PDOException $Exception)
            {
                $this->requeteOk = false;
                $this->errormsg = $c->errorInfo();
                $sql->rollback();
                $c->closeCursor();
                $this->Id = 0;
			}
        }
    }

    /**
     * Supprime un Document de la base
     */
    public function delete()
    {
        $sql = SQL::getInstance()->getConnection();

        $query = 'DELETE FROM Document WHERE IdDocument = :id';
        $c = $sql->prepare($query);
        $c->bindParam(':id', $this->Id, PDO::PARAM_INT);
        $c->execute();
    }

    // Fonciton Upload
    /**
     *
     * @param mixed $FILE Variable $_FILES
     * @param string $dossier path pour l'upload
     * @return string message d'erreur
     */
    public function upload($FILE, $dossier, $extensions = array())
    {
        if (!empty($dossier) && isset($FILE))
        {
            if(!is_dir(DS.$dossier))
            {
                mkdir(DS.$dossier);
            }
            $fichier = basename($FILE['name']);
            $taille_maxi = 1000000;
            $taille = filesize($FILE['tmp_name']);
			if(empty($extensions))
			{
				$extensions = array('.csv');
				
			}
            $extension = strrchr($FILE['name'], '.');
            //Debut des verifications de securite...
            if (!in_array($extension, $extensions)) //Si l'extension n'est pas dans le tableau
            {
                $erreur = 'Erreur : Vous devez uploader un fichier de type ' . implode(',', $extensions) . '...';
            }
            if ($taille > $taille_maxi)
            {
                $erreur = 'Erreur : Le fichier est trop gros...';
            }
            if (!isset($erreur)) //S'il n'y a pas d'erreur, on upload
            {
                //On formate le nom du fichier ici...
                $fichier = strtr($fichier,
                                'ÀÁÂÃÄÅÇÈÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèêëìíîïðòóôõöùúûüýÿ',
                                'AAAAAACEEEIIIIOOOOOUUUUYaaaaaaceeeiiiioooooouuuuyy');
                $fichier = preg_replace('/([^.a-z0-9]+)/i', '-', $fichier);
                if (move_uploaded_file($FILE['tmp_name'], $dossier . $fichier)) //Si la fonction renvoie TRUE, c'est que ça a fonctionne...
                {
                    return array("bool"=>true,"msg"=>$dossier.$fichier);
                }
            }
        }

        return array("bool"=>false,"msg"=>$erreur);
    }

    /*     * ***************** GETTER / SETTER ******************** */

    /**
     *
     * @return int
     */
    public function getId()
    {
        return $this->Id;
    }

    /**
     *
     * @return int
     */
    public function getIdStage()
    {
        return $this->IdStage;
    }

    /**
     *
     * @param int $IdStage
     * @return mixed
     */
    public function setIdStage($IdStage)
    {
        $errTab = array("boolOk" => true, "errmsg" => "");
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        if (isset($IdStage) && !empty($IdStage))
        {
            $this->IdStage = $IdStage;
            $this->errormsg = "";
        }
        else
        {
            $errTab["boolOk"] = false;
            $errTab["errmsg"] = "L'Id du stage doit etre defini !";
            $this->IdStage = 0;
        }
        return $errTab;
    }

    /**
     *
     * @return string
     */
    public function getPath()
    {
        return $this->Path;
    }

    /**
     *
     * @param string $Path
     */
    public function setPath($Path)
    {
        $this->Path = $Path;
    }

    /**
     *
     * @return int
     */
    public function getDateUpload()
    {
        return $this->DateUpload;
    }

    /**
     *
     * @param int $DateUpload
     * @return mixed
     */
    public function setDateUpload($DateUpload)
    {
        $errTab = array("boolOk" => true, "errmsg" => "");
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        if (isset($DateUpload) && !empty($DateUpload) && strlen($DateUpload) == 10)
        {
            $this->DateUpload = $DateUpload;
            $this->errormsg = "";
        }
        else
        {
            $errTab["boolOk"] = false;
            $errTab["errmsg"] = "La date est mal defini";
            $this->DateUpload = 0;
        }
        return $errTab;
    }

    /**
     *
     * @return int
     */
    public function getIdTypeDocument()
    {
        return $this->Type;
    }

    /**
     * @see TypeDocument
     * @param int $Type
     * @return mixed
     */
    public function setIdTypeDocument($Type)
    {
        $errTab = array("boolOk" => true, "errmsg" => "");
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        if (isset($Type) && !empty($Type))
        {
            $this->Type = $Type;
            $this->errormsg = "";
        }
        else
        {
            $errTab["boolOk"] = false;
            $errTab["errmsg"] = "Le Type doit etre defini !";
            $this->Type = 0;
        }
        return $errTab;
    }

    /**
     *
     * @return int
     */
    public function getIdRequiredDocument()
    {
        return $this->Required;
    }

    /**
     * @see TypeDocument
     * @param int $Type
     * @return mixed
     */
    public function setIdRequiredDocument($Required)
    {
        $errTab = array("boolOk" => true, "errmsg" => "");
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        if (isset($Required) && !empty($Required))
        {
            $this->Required = $Required;
            $this->errormsg = "";
        }
        else
        {
            $errTab["boolOk"] = false;
            $errTab["errmsg"] = "L'IdRequiredDocument doit etre defini !";
            $this->Required = 0;
        }
        return $errTab;
    }

    /**
     *
     * @return string
     */
    public function getStatut()
    {
        return $this->Statut;
    }

    /**
     *
     * @param string $Statut
     * @return mixed 
     */
    public function setStatut($Statut)
    {
        $errTab = array("boolOk" => true, "errmsg" => "");
        //Verif Type + verif Nulle, si bon mis a jour, sinon message erreur
        if (isset($Statut) && !empty($Statut) &&
                ($Statut == "prive" || $Statut == "public"))
        {
            $this->Statut = $Statut;
            $this->errormsg = "";
        }
        else
        {
            $errTab["boolOk"] = false;
            $errTab["errmsg"] = "Le Type doit etre defini !";
            $this->Statut = 0;
        }
        return $errTab;
    }
	
	/**
     *
     * @param int $idStage
     * @return liste de document liée a un stage précis  
     */
	public function getListDocumentByIdStage($idStage){
		$sql = SQL::getInstance()->getConnection();

        $query = "SELECT * FROM Document d WHERE d.IdStage = :idStage AND idTypeDocument>0";
		$c = $sql->prepare($query);
        $c->bindParam(':idStage', $idStage, PDO::PARAM_INT);
		$c->execute();
        $result = $c->fetchAll(PDO::FETCH_OBJ);
		

        if (!empty($result))
        {
            return $result;
        }
        return array();
	}
	
	/**
     *
     * @param int $idStage, int $idTypeDocument
     * @return liste de document liée a un stage précis  et correspondant à un Type document prècis, elle retourne une liste de taille 0 ou 1
     */
	public static function getListDocumentByIdStageAndIdTypeDocument($idStage, $idTypeDocument){
		$sql = SQL::getInstance()->getConnection();

        $query = "SELECT * FROM Document d WHERE d.IdStage = :idStage AND d.IdTypeDocument = :idTypeDocument";
		$c = $sql->prepare($query);
        $c->bindParam(':idStage', $idStage, PDO::PARAM_INT);
		$c->bindParam(':idTypeDocument', $idTypeDocument, PDO::PARAM_INT);
		$c->execute();
        $result = $c->fetchAll(PDO::FETCH_OBJ);
		
        if (!empty($result))
        {
            return $result;
        }
        return array();
	}
	
	
    /**
     * Retourne un document existant ou en créé un
     * @param int $idStage
     * @param int $idRequiredDocument
     * @return document
     */
    public static function getDocumentByIdSAndIdRD($idStage, $idRequiredDocument){
        $sql = SQL::getInstance()->getConnection();

        $query = "SELECT * FROM Document d WHERE d.IdStage = :idStage AND d.IdRequiredDocument = :idRequiredDocument";
		$c = $sql->prepare($query);
        $c->bindParam(':idStage', $idStage, PDO::PARAM_INT);
		$c->bindParam(':idRequiredDocument', $idRequiredDocument, PDO::PARAM_INT);
		$c->execute();
        $doc = $c->fetch(PDO::FETCH_OBJ);
        if(empty($doc)){
            $doc = new Document();
            $doc->setIdStage($idStage);
            $doc->setIdRequiredDocument($idRequiredDocument);
            $doc->setStatut("prive");
        }
        return $doc;
    }

}

?>